package leetcode._07_贪心;

import org.junit.Test;

import java.util.Arrays;

/**
 * @author pppppp
 * @date 2022/3/21 16:26
 * 给定一个区间的集合 intervals ，其中 intervals[i] = [starti, endi] 。
 * 返回 需要移除区间的最小数量，使剩余区间互不重叠 。
 * <p>
 * 示例 1:
 * <p>
 * 输入: intervals = [[1,2],[2,3],[3,4],[1,3]]
 * 输出: 1
 * 解释: 移除 [1,3] 后，剩下的区间没有重叠。
 * 示例 2:
 * <p>
 * 输入: intervals = [ [1,2], [1,2], [1,2] ]
 * 输出: 2
 * 解释: 你需要移除两个 [1,2] 来使剩下的区间没有重叠。
 * 示例 3:
 * <p>
 * 输入: intervals = [ [1,2], [2,3] ]
 * 输出: 0
 * 解释: 你不需要移除任何区间，因为它们已经是无重叠的了。
 *  
 * <p>
 * 提示:
 * <p>
 * 1 <= intervals.length <= 105
 * intervals[i].length == 2
 * -5 * 104 <= starti < endi <= 5 * 104
 */
public class _435_无重叠区间 {

    /*右侧排序*/
    @Test
    public void T_0() {
        int[][][] nums = {
                {{-52, 31}, {-73, -26}, {82, 97}, {-65, -11}, {-62, -49}, {95, 99}, {58, 95}, {-31, 49}, {66, 98}, {-63, 2}, {30, 47}, {-40, -26}},
                {{1, 2}, {2, 3}, {3, 4}, {1, 3}},
                {{1, 2}, {1, 2}, {1, 2}},
                {{1, 2}, {2, 3}}
        };
        int[] ans = {7, 1, 2, 0};
        for (int i = 0; i < nums.length; i++) {
            // System.out.println(eraseOverlapIntervals(nums[i]) == ans[i]);
            System.out.println(eraseOverlapIntervals_review(nums[i]) == ans[i]);
        }
    }

    public int eraseOverlapIntervals_review(int[][] intervals) {
        Arrays.sort(intervals, (o1, o2) -> {
            if (o1[1] == o2[1]) {
                return o2[0] - o1[0];
            }
            return o1[1] - o2[1];
        });
        int cnt = 0, right = intervals[0][1];
        for (int i = 1; i < intervals.length; i++) {
            if (intervals[i][0] < right) {
                cnt++;
            }else {
                right = intervals[i][1];
            }
        }

        return cnt;
    }

    public int eraseOverlapIntervals(int[][] intervals) {
        Arrays.sort(intervals, (o1, o2) -> {
            if (o1[1] == o2[1]) {
                return o1[0] - o2[0];
            }
            return o1[1] - o2[1];
        });
        int cnt = 1, pos = intervals[0][1];
        for (int[] interval : intervals) {
            if (interval[0] >= pos) {
                cnt++;
                pos = interval[1];
            }
        }
        return intervals.length - cnt;
    }
}
